﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using JinianNet.JNCms.Data;
using JinianNet.JNCms.Filters;
using JinianNet.JNCms.Models;

namespace JinianNet.JNCms.Controllers
{
    public class ManageController : ControllerBase
    {
        public ActionResult Test()
        {
            return View("MVC ALL PAGE Test");
        }

        [ManagerFilter()]
        public ActionResult Main()
        {
            JinianNet.JNCms.Data.ICategory category = Data.DataAccess.CreateCategory();
            ViewBag.Category = Data.DataAccess.CreateCategory().GetList(0,false);
            ViewBag.ModuleClassify = Data.DataAccess.CreateClassify().GetList(0, 1);
            return View();
        }

        public ActionResult Left()
        {
            JinianNet.JNCms.Data.ICategory category = Data.DataAccess.CreateCategory();
            ViewBag.Category = Data.DataAccess.CreateCategory().GetList(0,false);
            ViewBag.ModuleClassify = Data.DataAccess.CreateClassify().GetList(0, 1);
            return View();
        }


        public ActionResult Right()
        {
            return View();
        }


        public ActionResult Top()
        {
            return View();
        }

        public ActionResult Bottom()
        {
            return View();
        }

        [ManagerFilter()]
        public ActionResult Index()
        {
            ViewBag.OSVersion = Environment.OSVersion.ToString();
            ViewBag.NetVersion = Environment.Version.ToString();
            ViewBag.ServiceName = Server.MachineName;
            ViewBag.SiteLength = Convert.ToString(JinianNet.IO.File.DirectorSize(new System.IO.DirectoryInfo(Server.MapPath("~/"))) / 1024 / 1024) + "M";
            ViewBag.ServiceIP = Request.ServerVariables["LOCAL_ADDR"];
            ViewBag.ServicePort = Request.ServerVariables["SERVER_PORT"];
            ViewBag.IISVersion = Request.ServerVariables["SERVER_SOFTWARE"];
            ViewBag.ServicePath = Server.MapPath("~/");
            //ViewBag.MachineName =  Server.
            return View();
        }


        public ActionResult Message(bool Success, string Content, string Url)
        {
            ViewBag.Success = true;
            ViewBag.Content = Content;
            ViewBag.Url = Url;
            return View();
        }

        [ManagerFilter()]
        [HttpGet]
        public ActionResult Setting()
        {
            return View((object)Config.SiteConfig);
        }

        [ManagerFilter()]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Setting(FormCollection form)
        {
            Dictionary<string, string> dictionary = Config.SiteConfig;
            string[] item = new string[dictionary.Count];
            dictionary.Keys.CopyTo(item, 0);
            foreach (string key in item)
            {
                if (form[key] != null)
                {
                    dictionary[key] = form[key];
                }
            }
            Config.Write(dictionary, "Site");
            return Content(Config.GetTips("设置文件更新成功！", Url.Action("Setting", "Manage"), true));// View((object)dictionary);
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Login(string account, string password)
        {
            IUsers dal = Data.DataAccess.CreateUsers();
            Users model = dal.GetItem(account);
            if (model == null)
            {
                return Content(Config.GetTips("用户不存在", Url.Action("Login", "Manage"), false));
            }
            else
            {
                if (model.Status != 0)
                {
                    return Content(Config.GetTips(string.Concat("该用户", Users.GetStatusName(model.Status), "，暂时无法登陆！"), Url.Action("Login", "Manage"), false));
                }
                if (model.FailedPasswordAttemptCount > 3 && ((TimeSpan)(model.LastFailedPasswordAttempTime - DateTime.Now)).Hours < 1)
                {
                    return Content(Config.GetTips("该用户密码连续错误超过3次，1小时内禁止登录", Url.Action("Login", "Manage"), false));
                }
                if (model.UserPassword.Equals(Common.Utils.MD5(password), StringComparison.OrdinalIgnoreCase))
                {
                    dal.LoginSuccess(account, Common.Utils.GetIP(), DateTime.Now);
                    Session["User"] = model;
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                                     1,
                                     "User",
                                     DateTime.Now,
                                     DateTime.Now.AddMinutes(30),
                                     false,
                                     model.Account);
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    System.Web.HttpCookie authCookie = new System.Web.HttpCookie("User", encryptedTicket);
                    ControllerContext.HttpContext.Response.Cookies.Add(authCookie);
                    return Redirect(Url.Action("Main", "Manage"));
                }
                else
                {
                    dal.LoginFail(model.Account, Common.Utils.GetIP(), DateTime.Now);
                    return Content(Config.GetTips(string.Concat("密码错误，<br />连续错误3次后将在1小时内禁止登录，<br />当前已经错误次数：", (model.FailedPasswordAttemptCount + 1).ToString()), Url.Action("Login", "Manage"), false));
                }
            }
        }
    }
}
